package snapex.core.fallback;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import com.netflix.hystrix.exception.HystrixTimeoutException;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class FeeCloudsServiceFallbackProvider implements FallbackProvider {

	@Override
	public String getRoute() {
		return "invoice-service"; 
	}

	@Override
	public ClientHttpResponse fallbackResponse(String route, final Throwable cause) {
		
		log.error("***invoice-service fallbackResponse*****", cause);
		
		HttpStatus httpStatus;
		if (cause instanceof HystrixTimeoutException) {
			httpStatus = HttpStatus.GATEWAY_TIMEOUT;
        }else if(cause instanceof com.netflix.client.ClientException) {
        	httpStatus = HttpStatus.SERVICE_UNAVAILABLE;
        }		
		else {
        	httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
        }
		
		return new ClientHttpResponse() {
	            @Override
	            public HttpStatus getStatusCode() throws IOException {
	                return httpStatus;
	            }

	            @Override
	            public int getRawStatusCode() throws IOException {
	                return httpStatus.value();
	            }

	            @Override
	            public String getStatusText() throws IOException {
	                return httpStatus.getReasonPhrase();
	            }

	            @Override
	            public void close() {

	            }

	            @Override
	            public InputStream getBody() throws IOException {
	                return new ByteArrayInputStream(new FallbackResponse(503/*SERVICE_UNAVAILABLE*/,"invoice-service is unavailable").toJsonString().getBytes());
	            }

	            @Override
	            public HttpHeaders getHeaders() {
	                HttpHeaders headers = new HttpHeaders();
	                headers.setContentType(MediaType.APPLICATION_JSON);
	                return headers;
	            }
	        };
	}	
}
